package main

import (
	"coarse_score_cal_flow/config"
	"coarse_score_cal_flow/ginmiddleware"
	"coarse_score_cal_flow/logs"
	"coarse_score_cal_flow/middleware/mysql"
	"coarse_score_cal_flow/router"
	"coarse_score_cal_flow/router/actor"
	"coarse_score_cal_flow/router/album"
	"coarse_score_cal_flow/router/noroute"
	"coarse_score_cal_flow/router/user"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// 优势:hook多(eg:email hook)
var Environment = "production"
var configFile = flag.String("config", "application.yaml", "config file")

func main() {
	config.InitConfig(configFile)
	log := logs.InitConfig()
	r := router.Init(
		album.LoadRouter,
		user.LoadRouter,
		noroute.LoadRouter,
		actor.LoadRouter,
	)
	mysql.InitMySQL()

	r.Use(func(c *gin.Context) {
		startTime := time.Now() // 记录开始时间

		// 继续处理请求
		c.Next()

		// 记录结束时间
		endTime := time.Now()
		elapsed := endTime.Sub(startTime)

		// 打印耗时
		log.Infof("Request %s %s took %v\n", c.Request.Method, c.Request.URL.Path, elapsed)
	})

	// 按注册顺序执行, 先全局->路由组->单个路由上的中间件
	r.Use(ginmiddleware.StatCost(), ginmiddleware.GinBodyLogMiddleware)

	r.GET("/routes", ginmiddleware.MwForUrl, func(c *gin.Context) {
		routes := r.Routes()
		for _, route := range routes {
			fmt.Printf("Path: %s, Method: %s\n", route.Path, route.Method)
		}
		value, exists := c.Get("user")
		if exists {
			c.String(http.StatusOK, "Check console for routes: context: %s", value)
		}
	})

	r.Run(":8080")
}
